<template>
  <div>
    <div class="flex flex-col h-full">
      <SearchContainer @search="getData" @reset="() => formRef.resetFields()">
        <a-form ref="formRef" class="flex-1" :model="formState" :colon="false">
          <a-form-item name="mcbh" label="手术日期" class="w-[320px]">
            <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </a-form-item>
        </a-form>
      </SearchContainer>
      <a-card class="mt-2">
        <div class="flex justify-end mb-3">
          <BaseExport type="运维" name="服用方法" code="000719" :search-params="formState">导出</BaseExport>
        </div>
        <BaseTable v-if="columns.length && !loading" :loading="loading" :columns="columns" :data-source="tableData" bordered fill :pagination="pagination" />
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import dayjs from 'dayjs'
import SearchContainer from '@/components/SearchContainer'
import BaseTable from '@/components/BaseTable'

const formRef = ref(null)
const formState = ref({
  dateRange: [dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const columns = ref([])
const { loading, tableData, getData, pagination } = useTable({
  url: '/oprOperation/opr/getSurgicalClassificationStatisticsList',
  immediate: true,
  formatParams: () => {
    return {
      stdate: formState.value.dateRange?.[0],
      eddate: formState.value.dateRange?.[1]
    }
  },
  onSuccess: (res) => {
    if (res && res.length > 0) {
      const idx = findObjectWithMostKeyValuePairs(res)
      columns.value = Object.keys(res[idx]).map((item) => {
        const align = item === '序号'
        const width = item === '序号' ? 60 : ''
        return { title: item, dataIndex: item, align, ellipsis: true, width }
      })
      const xhData = columns.value.find((item) => {
        return item.title === '序号'
      })
      const noXhData = columns.value.filter((item) => {
        return item.title !== '序号'
      })
      columns.value = [xhData, ...noXhData]
    }
    return res
  }
})

const findObjectWithMostKeyValuePairs = (arr) => {
  const arrObj = []
  arr.forEach((item, index) => {
    arrObj.push({ num: Object.keys(item).length, idx: index })
  })
  const max = arrObj.sort((a, b) => b.num - a.num)[0].idx // 40
  return max // 返回键值对最多的对象
}
</script>
